//
//  XSVideoClipViewController.m
//  AudioVideo
//
//  Created by xueshan1 on 2019/10/31.
//  Copyright © 2019 xueshan1. All rights reserved.
//

#import "XSVideoClipViewController.h"

@interface XSVideoClipViewController ()<UIScrollViewDelegate,XSVideoCutoutViewDelegate>
{
    BOOL _needCutting;

}
@property(nonatomic,strong)XSVideoCutoutView *cutView;
@property(nonatomic,strong)NSMutableArray *thumbsArray;
@property(nonatomic,strong)UIScrollView *scrollView;
//video
@property(nonatomic,assign)CGFloat cutStartTimePercent;
@property(nonatomic,assign)CGFloat cutEndTimePercent;

@end

@implementation XSVideoClipViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    
    if (self.photoModel) {
  
        [XSPhotosManager requestVideoAVAsset_ForAsset:self.photoModel.asset progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
            
        } completion:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary *info) {
            self.avasset = asset;
            [[XSAVPlayer shareInstance]playVideoWithAVAsset:asset onPlayView:self.view belowView: self.safeView];
            [self generateThumbnails];
        }];
        
        
    }else if (self.videoURL ) {
        //在videDidLoad 调用,有时候,刚录制的视频,获取不到
        [[XSAVPlayer shareInstance]playVideoWithURLString:self.videoURL.absoluteString onPlayView:self.view belowView:self.safeView isLocalFile:YES];
        
        [self generateThumbnails];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
 
}

- (void)setupUI{
    XSVideoCutoutView *cutView = [[XSVideoCutoutView alloc]initWithFrame:CGRectMake(50, kHeight - 100, kWidth - 100, 70)];
    cutView.cutDelegate = self;
    [self.view addSubview:cutView];
    self.cutView = cutView;
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(cutView.left + cutView.leftRightInset, cutView.top, cutView.width - 2 * cutView.leftRightInset, cutView.height)];
    scrollView.delegate = self;
    [self.view insertSubview:scrollView belowSubview:cutView];
    self.scrollView = scrollView;
    
    
}

#pragma mark - 缩略图
- (void)generateThumbnails{
    [XSAVTools generateThumbnailsWithURL:self.videoURL orAsset:self.avasset completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error, NSInteger imageCount) {
        if (!error) {
            if (result == AVAssetImageGeneratorSucceeded) {
                UIImage *thumbImage = [UIImage imageWithCGImage:image];
                [self.thumbsArray addObject:thumbImage];
                //                NSLog(@"缩略图:%ld -- %@",self.thumbsArray.count, thumbImage);
                if (self.thumbsArray.count == imageCount ) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        CGFloat wid = self.scrollView.width / self.thumbsArray.count;
                        for (int i = 0 ; i<self.thumbsArray.count; i++) {
                            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*wid, 0, wid, self.scrollView.height)];
                            imageView.image = self.thumbsArray[i];
                            [self.scrollView addSubview:imageView];
                        }
                        
                    });
                }
            }
            
        }else{
            NSLog(@"缩略图Fail:%@",error);
        }
    }];
}

#pragma mark - 裁剪
- (void)cuttingVideo {
    NSString *exportPath = [XSFileManager tempFilePathWithPathComponent:@"test.mov"];
    NSURL *exportUrl = [NSURL fileURLWithPath:exportPath];
    [XSFileManager deleteTempFileWithPathComponent:@"test.mov"];
    
//    AVAsset *asset = [AVAsset assetWithURL:self.videoURL];
    AVAsset *asset = nil;
    if (self.videoURL) {
        asset = [AVAsset assetWithURL:self.videoURL];
    }else if (self.avasset){
        asset = self.avasset;
    }
    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
    exportSession.outputURL = exportUrl;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
    //截取的时间段
    CGFloat totalTime = [XSAVPlayer shareInstance].sf_totalTime;
    CMTime start = CMTimeMake(self.cutStartTimePercent * totalTime, 1);
    CMTime duration = CMTimeMake((self.cutEndTimePercent - self.cutStartTimePercent) * totalTime, 1);
    CMTimeRange timeRange = CMTimeRangeMake(start, duration);
    exportSession.timeRange = timeRange;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (exportSession.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Export completed");
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"编辑后的视频路径： %@",exportPath);
                MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.label.text = @"保存到相册...";
                [XSPhotosManager saveToPhotoLibrary:exportUrl completion:^(NSError * _Nonnull error) {
                    [hud hideAnimated:YES];
                    
                    XSVideoEditeViewController *editVC = [XSVideoEditeViewController new];
                    editVC.avasset = [AVURLAsset assetWithURL:exportUrl];
                    [self.navigationController pushViewController:editVC animated:YES];
                }];
            });
        } else if (exportSession.status == AVAssetExportSessionStatusFailed) {
            NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
        }
        
    }];
    
}

- (void)videoCutoutWithStartPercent:(CGFloat)startP endPercent:(CGFloat)endP durationPercent:(CGFloat)durationP{
     NSLog(@"left:%f   right:%f",startP, endP);
    self.cutStartTimePercent = startP;
    self.cutEndTimePercent = endP;
    _needCutting = YES;
    if ([XSAVPlayer shareInstance].playState == XSAVPlayerState_Playing) {
        [XSAVPlayer shareInstance].playStartTimePercent = startP;
        [XSAVPlayer shareInstance].playStopTimePercent = endP;
        [[XSAVPlayer shareInstance] setProgressValus:startP];//seek
    }
    
    
}

- (NSMutableArray *)thumbsArray{
    if (!_thumbsArray) {
        _thumbsArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _thumbsArray;
}


- (IBAction)newtBtnAction:(id)sender {
    if (_needCutting) {
        [self cuttingVideo];
    }else{
        XSVideoEditeViewController *editVC = [XSVideoEditeViewController new];
        editVC.photoModel = self.photoModel;
        editVC.videoURL = self.videoURL;
        editVC.avasset = self.avasset;
        [self.navigationController pushViewController:editVC animated:YES];
    }

}

 

@end
